<?php

namespace Question\Service;

/**
 * 答题业务
 */
class Answer {
	private $_daoQuestionModel;
	private $_daoUserModel;

	/**
	 * 构造函数
	 */
	public function __construct() {
		$this->_daoQuestionModel = \Lsf\Loader::Model('DaoQuestion', TRUE);
		$this->_daoUserModel = \Lsf\Loader::Model('DaoUser', TRUE);
	}

	/**
	 * 验证答案公众号
	 */
	public function checkAnswerVx($uid, $questionSetId, $userAnswer){
		// 查询题目答案
		$where = [
//			'set_id' => $questionSetId,
			'status' => 1,
		];
		$questionList = $this->_daoQuestionModel->select('question_id,question_desc,answer', $where, 'question_id ASC', 999, FALSE);
		// 校验答案
		$answerList = [];
		$questionIdMap = [];
		foreach ($questionList as $item){
			$answerList[$item['question_id']] = $item['answer'];
			$questionIdMap[$item['question_id']] = $item;
		}
		$userPoints = 0;
		$errorQuestions = [];
		foreach($userAnswer as $item){
			if(trim($item['answer']) == $answerList[$item['question_id']]){
				$userPoints++;
			}else{
				$errorQuestions[] = $questionIdMap[$item['question_id']];
			}
		}
		$userPoints = $userPoints * 10;
		// 计分
		$user = [
			'point' => $userPoints,
		];
		$where = [
			'user_id' => $uid,
			'point' => ['lt' , $userPoints]
		];
		$rows = $this->_daoUserModel->update($user, $where);
		if($rows !== 1 && $rows != 0){
			\Lsf\Loader::plugin('Log')->error(DATABASE_OPERATE_FAIL, [
				'model_name' => 'dao_user',
				'update'     => $user,
				'where'      => $where,
			]);
			return FALSE;
		}
		return [
			'uid' => $uid,
			'point' => $userPoints,
//			'error_questions' => $errorQuestions,
			'error_questions' => [],

		];
	}

	/**
	 * 验证答案扫码
	 */
	public function checkAnswerCode($uid, $point){
		// 解析分数
		$b = intval($point / 100);
		$s = intval($point % 100 / 10);
		$g = intval($point % 10);
		if($b == 2){
			$point = 100;
		}if($b == 1){
			$point = $s * 10 ;
		}
		// 积分
		$user = [
			'point' => $point,
		];
		$where = [
			'user_id' => $uid,
			'point' => ['lt' , $point]

		];
		$rows = $this->_daoUserModel->update($user, $where);
		if($rows !== 1 && $rows != 0){
			\Lsf\Loader::plugin('Log')->error(DATABASE_OPERATE_FAIL, [
				'model_name' => 'dao_user',
				'update'     => $user,
				'where'      => $where,
			]);
			return FALSE;
		}
		return [
			'uid' => $uid,
			'point' => $point,
		];
	}
}